import React from 'react'
import {POST} from '../com/send'
import './signin.css'
import md5 from 'md5'
class login extends React.Component{
    constructor(props){
        super(props);
        this.state = {error:0,msg:"",email:"",password:""}
    }
    componentDidMount(){
        if(sessionStorage.user){
            const {history} = this.props;
            history.replace("/console");
        }
    }
    syaError(){
        if(this.state.error!==0){
            return (
                <div className="alert alert-danger" role="alert">{this.state.msg}</div>
            );
        }
    }
    handleEmailChange(e){
        this.setState({email:e.target.value})
    }
    handlePasswordChange(e){
        this.setState({password:e.target.value})
    }
    login(){
        const param = `email=${this.state.email}&password=${md5(this.state.password)}`;
        POST("/api/user/login",param).then((resp) => {
            if(resp.code !== 0){
                this.setState({error:resp.code,msg:resp.msg});
            }else{
                sessionStorage.user = JSON.stringify(resp.data);
                const {history} = this.props;
                history.replace("/console");
            }
        })
    }
    render(){
        return (
            <div className="container">
                <div className="form-signin">
                    <h2 className="form-signin-heading">登录</h2>
                    <label htmlFor="inputEmail" className="sr-only">Email address</label>
                    <input type="email" id="inputEmail" name="a-email" className="form-control" placeholder="请输入登录邮箱" onChange={(e)=>{this.handleEmailChange(e)}}/>
                    <label htmlFor="inputPassword" className="sr-only">Password</label>
                    <input type="password" id="inputPassword" name="a-password" className="form-control" onChange={(e) => {this.handlePasswordChange(e)}} placeholder="请输入登录密码"/>
                    {this.syaError()}
                    <button className="btn btn-lg btn-primary btn-block" onClick={()=>this.login()}>登录</button>
                </div>
            </div>
        );
    }
}
export default login;